package chapter5_基础构建模块.构建高效结果可伸缩的缓存;

import annotation.ThreadSafe;

import java.io.IOException;
import java.util.concurrent.*;

@ThreadSafe
public class Memoizer<A, V> implements Computable<A, V> {
    private final ConcurrentHashMap<A, Future<V>> cache = new ConcurrentHashMap<>();
    private final Computable<A, V> c;

    public Memoizer(Computable<A, V> c) {
        this.c = c;
    }

    @Override
    public V compute(A arg) throws InterruptedException {
        while (true) { //解决缓存污染，future缓存有可能不是正常结果，而是异常，或者刚被取消的状态
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> eval = new Callable<V>() {
                    @Override
                    public V call() throws Exception {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<>(eval);
                // 原子方法putIfAbsent，保障复合操作(没有则添加)的原子性
                f = cache.putIfAbsent(arg, ft);
                if (f == null) {
                    f = ft;
                    // 同步!!!执行结果运算，之前的putIfAbsent只是注册到cache中
                    ft.run();
                }
                try {
                    // 获取结果，有可能是正常结果、取消结果(取消异常)、或异常结果(运行中碰到的异常)
                    f.get();
                } catch (CancellationException e) {
                    cache.remove(arg, f);
                } catch (ExecutionException e) { //ExecutionException会封装原始异常信息
                    throw launderThrowable(e.getCause());
                }
            }
        }
    }

    public static RuntimeException launderThrowable(Throwable t) {
        if (t instanceof RuntimeException) {
            return (RuntimeException) t;
        } else if (t instanceof Error) {
            throw (Error) t;
        } else {
            throw new IllegalStateException("Not unchecked", t);
        }
    }

    // 演示CancellationException
    public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
        FutureTask<Integer> futureTask = new FutureTask<>(() -> {
            System.out.println("开始执行");
            TimeUnit.SECONDS.sleep(10);
            return 10;
        });
        // 注意run方法是同步执行
//        futureTask.run();
        // 取消任务时不管是否允许中断，均抛出CancellationException
        futureTask.cancel(false);
//        futureTask.cancel(true);
        TimeUnit.SECONDS.sleep(3);
        // 这里打断点，看是否调用get时抛出异常
        System.out.println(futureTask.get());
        System.in.read();
    }
}

@FunctionalInterface
interface Computable<A, V> {
    V compute(A arg) throws InterruptedException;
}
